'use strict';

const express = require('express');
const path = require('path');
const multer = require('multer');
const fs = require('fs');
const app = express();
const router = express.Router();
const bodyParser = require('body-parser');

// 创建 application/x-www-form-urlencoded 编码解析
const urlencodedParser = bodyParser.urlencoded({ extended: false });

app.use(express.static('public'));
app.use('/upload', express.static('upload'));

function readFileList(dir, filesList = []) {
  try {
    const files = fs.readdirSync(dir);
    files.forEach((item, index) => {
      let fullPath = path.join(dir, item);
      const stat = fs.statSync(fullPath);
      const statTime = stat.mtime;
      if (stat.isDirectory()) {
        filesList.push({
          name: item,
          time: statTime,
          children: [],
        });
        const filesChilds = fs.readdirSync(fullPath);
        filesChilds.forEach((itemChilds, indexChilds) => {
          let fullPathChilds = path.join(fullPath, itemChilds);
          const statChilds = fs.statSync(fullPathChilds);
          const statChildsTime = statChilds.mtime;
          if (statChilds.isDirectory()) {
            filesList[index].children.push({
              name: itemChilds,
              time: statChildsTime,
            });
          }
        });
      }
    });
    return filesList;
  } catch (e) {
    return [];
  }
}

// 查看所有文件
app.get('/list', async function(req, res, next) {
  let filesList = [];
  const root = path.resolve(__dirname, `./upload`);
  filesList = await readFileList(root, filesList);
  res.json(filesList);
});

function delDir(path) {
  try {
    let files = [];
    if (fs.existsSync(path)) {
      files = fs.readdirSync(path);
      files.forEach((file, index) => {
        let curPath = path + '/' + file;
        if (fs.statSync(curPath).isDirectory()) {
          delDir(curPath); //递归删除文件夹
        } else {
          fs.unlinkSync(curPath); //删除文件
        }
      });
      fs.rmdirSync(path);
    }
  } catch (e) {
    console.log(e);
  }
}

// 删除一个文件
app.post('/del', urlencodedParser, async function(req, res, next) {
  let projectname = req.body.projectname;
  let projectversion = req.body.projectversion;
  if (!!projectname || !!projectversion) {
    let tempPath = path.resolve(__dirname, `./upload/${projectname}/${projectversion}`);
    await delDir(tempPath);
    res.json({ code: 0, message: `删除成功` });
  } else {
    res.json({ code: 1, message: `参数错误` });
  }
});

// 递归创建目录 同步方法
function createFolder(dirname) {
  if (fs.existsSync(dirname)) {
    return true;
  } else {
    if (createFolder(path.dirname(dirname))) {
      fs.mkdirSync(dirname);
      return true;
    }
  }
}

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    let projectname = req.body.projectname;
    let projectversion = req.body.projectversion;
    if (!!projectname) {
      //save path
      //get folder path width regexp
      const folderExec = new RegExp('^(.*)/([^/]+)$').exec(file.originalname);
      let folder = '';
      if (folderExec) {
        folder = folderExec[1];
        //  去除本级根元素文件夹 path.sep
        folder = folder.split('/');
        if (folder.length > 0) {
          folder = folder.splice(1, folder.length - 1);
        }
        folder = folder.join('/');
        // let tempFolder = path.resolve(__dirname, `./upload/${projectname}/${projectversion}`)
        let tempFolder = path.resolve(__dirname, `./upload/${projectname}/${projectversion}/${folder}/`);
        createFolder(tempFolder);
      }
      // cb(null, path.resolve(__dirname, `./upload/${projectname}/${projectversion}`))
      cb(null, path.resolve(__dirname, `./upload/${projectname}/${projectversion}/${folder}/`));
    }
  },
  filename: function(req, file, cb) {
    //save name
    const folderExec = new RegExp('^(.*)/([^/]+)$').exec(file.originalname);
    let folder = '';
    if (folderExec) {
      folder = folderExec[2];
    } else {
      folder = file.originalname;
    }
    cb(null, folder);
  },
});
const upload = multer({
  storage: storage,
  preservePath: true, //save originalname as perservepath. completion path.
}).any();

app.post('/uploaddir', upload, (req, res, next) => {
  res.redirect('./index.html');
});

app.listen(3333, () => {
  console.log('服务启动运行... 在浏览器打开页面： 127.0.0.1:3333 ');
});
